<template>
  <el-select
    v-model="selectedContactId"
    filterable
    remote
    :remote-method="handleSearch"
    :loading="loading"
    placeholder="请选择联系人"
    :disabled="disabled"
    @change="handleChange"
  >
    <el-option
      v-for="item in contactOptions"
      :key="item.id"
      :label="item.contactName"
      :value="item.id"
    >
      <span>{{ item.contactName }}</span>
      <span class="text-gray-500 ml-2">{{ item.phone }}</span>
    </el-option>
  </el-select>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { CustomerApi, type ContactPersonRespVO } from '@/api/oa/customer'

defineOptions({ name: 'ContactPersonSelect' })

const props = defineProps({
  modelValue: {
    type: [Number, String],
    default: undefined
  },
  customerId: {
    type: [Number, String],
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const loading = ref(false)
const contactOptions = ref<ContactPersonRespVO[]>([])
const selectedContactId = ref(props.modelValue)

// 加载联系人数据
const loadContacts = async (query?: string) => {
  if (!props.customerId) {
    contactOptions.value = []
    return
  }
  
  loading.value = true
  try {
    const { list } = await CustomerApi.getCustomerContactPage({
      pageNo: 1,
      pageSize: 10,
      customerId: props.customerId,
      contactName: query
    })
    contactOptions.value = list
  } finally {
    loading.value = false
  }
}

// 监听 modelValue 变化
watch(() => props.modelValue, (val) => {
  selectedContactId.value = val
})

// 监听 customerId 变化
watch(() => props.customerId, (val) => {
  if (val) {
    loadContacts()
  } else {
    contactOptions.value = []
    selectedContactId.value = undefined
  }
}, { immediate: true })

// 搜索联系人
const handleSearch = (query: string) => {
  loadContacts(query)
}

// 选择变化
const handleChange = (value: number) => {
  emit('update:modelValue', value)
  const selected = contactOptions.value.find(item => item.id === value)
  emit('change', selected)
}

// 组件挂载时初始化数据
onMounted(() => {
  if (props.customerId) {
    loadContacts()
  }
})

defineExpose({ loadContacts })
</script> 